package com.big.common.mybatis.result;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.big.common.core.util.ConvertUtil;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

import java.io.Serial;
import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import java.util.function.Consumer;

/**
 * <p>
 * 增强型分页结果封装实体
 * </p>
 *
 * @param <T> 数据类型
 * @author shanguikui
 */
@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
public class PageResult<T> extends Page<T> implements Serializable {
    @Serial
    private static final long serialVersionUID = 1L;

    // 空分页常量（避免重复创建空对象）
    private static final PageResult<?> EMPTY = new PageResult<>();

    /**
     * 默认构造函数（创建空分页结果）
     */
    public PageResult() {
        this.setRecords(Collections.emptyList());
    }

    /**
     * 根据已有的 IPage<T> 构造 PageResult<T>
     */
    public PageResult(IPage<T> page) {
        if (page != null) {
            this.setRecords(page.getRecords());
            this.setCurrent(page.getCurrent());
            this.setSize(page.getSize());
            this.setTotal(page.getTotal());
        } else {
            this.setRecords(Collections.emptyList());
        }
    }

    public static <R> PageResult<R> of(long current, long size, long total, List<R> records) {
        PageResult<R> result = new PageResult<>();
        result.setRecords(records);
        result.setCurrent(current);
        result.setSize(size);
        result.setTotal(total);
        return result;
    }

    public <R> PageResult<R> mapTo(Class<R> dtoClass, Consumer<R> consumer) {
        List<R> rs = ConvertUtil.convertList(this.getRecords(), dtoClass, consumer);
        return of(this.getCurrent(), this.getSize(), this.getTotal(), rs);
    }

    public <R> PageResult<R> mapTo(Class<R> dtoClass) {
        return mapTo(dtoClass, null);
    }
}